package com.dxq.test.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dxq.test.App;
import com.dxq.test.common.AppManager;
import com.dxq.test.R;
import com.dxq.test.db.Group;
import com.dxq.test.db.GroupVaccine;
import com.dxq.test.db.Label;
import com.dxq.test.db.LabelVaccine;
import com.dxq.test.db.Pasture;
import com.dxq.test.db.TablesDao;
import com.dxq.test.db.Vaccine;
import com.dxq.test.utils.DialogClickListener;
import com.dxq.test.utils.DialogListClickListener;
import com.dxq.test.utils.MyUtil;
import com.dxq.test.view.GroupListDialog;
import com.j256.ormlite.dao.ForeignCollection;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Author: zsh
 * Date: 2023/11/17
 * Describe: 防治添加、修改、删除页面
 */
public class VaccineAddActivity extends AppCompatActivity implements View.OnClickListener, OnDateSetListener {

    public TablesDao tablesDao;

    private ImageView ivBack;
    private TextView tvTitle, tvSet;
    private Button btnSubmit;
    private LinearLayout llCode;
    private TextView tvCode, tvLabelName, tvTime, tvNextTime;
    private ImageView ivSelect;
    private EditText etType, etName, etRemark;
    private LinearLayout llGroup, llLabel;
    private TextView tvVaccineTitle, tvGroupName;
    private RadioGroup rgGroup;
    private RadioButton rbGroup, rbLabel;
    private CheckBox cbRemind;

    private Typeface font;

    private Vaccine vaccine;
    private Label labelSelect;
    private Group groupSelect;

    private int selectTime = 0;
    private TimePickerDialog mDialogAllTime;//选择时间控件

    private int selectGroup = 0;//防治目标  0：分群   1：个体
    private List<Group> groupList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //添加Activity到堆栈
        AppManager.getAppManager().addActivity(this);
        setContentView(R.layout.activity_vaccine_add);
        vaccine = (Vaccine) getIntent().getSerializableExtra("vaccine");
        //label = (Label) getIntent().getSerializableExtra("label");
        tablesDao = new TablesDao(this);
        font = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        initView();
        initTimePicker();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在appManager结束当前activity
        AppManager.getAppManager().finishActivity(this);
    }

    private void initView() {
        ivBack = findViewById(R.id.ivBack);
        tvTitle = findViewById(R.id.tvTitle);
        tvSet = findViewById(R.id.tvSet);
        tvTitle.setText("防治记录");
        tvSet.setText("删除");

        llCode = findViewById(R.id.llCode);
        tvCode = findViewById(R.id.tvCode);
        tvLabelName = findViewById(R.id.tvLabelName);
        tvGroupName = findViewById(R.id.tvGroupName);
        tvVaccineTitle = findViewById(R.id.tvVaccineTitle);
        tvTime = findViewById(R.id.tvTime);
        tvNextTime = findViewById(R.id.tvNextTime);
        llLabel = findViewById(R.id.llLabel);
        llGroup = findViewById(R.id.llGroup);
        rgGroup = findViewById(R.id.rgGroup);
        rbGroup = findViewById(R.id.rbGroup);
        rbLabel = findViewById(R.id.rbLabel);
        ivSelect = findViewById(R.id.ivSelect);
        cbRemind = findViewById(R.id.cbRemind);
        etName = findViewById(R.id.etName);
        etType = findViewById(R.id.etType);
        etRemark = findViewById(R.id.etRemark);
        btnSubmit = findViewById(R.id.btnSubmit);
        rgGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rbGroup:
                        selectGroup = 0;
                        showGroup();
                        break;

                    case R.id.rbLabel:
                        selectGroup = 1;
                        showGroup();
                        break;
                }
            }
        });

        if (null == vaccine) {
            tvSet.setVisibility(View.GONE);
            llCode.setVisibility(View.GONE);
            //rgGroup.setEnabled(true);
        } else {
            tvSet.setVisibility(View.VISIBLE);
            llCode.setVisibility(View.VISIBLE);
            //rgGroup.setEnabled(false);
            tvCode.setText(vaccine.getCode());
            etType.setText(vaccine.getType());
            etName.setText(vaccine.getName());
            if (vaccine.getGroup() != null) {
                groupSelect = vaccine.getGroup();
                tvGroupName.setText(groupSelect.getName());
                selectGroup = 0;
            }
            if (vaccine.getLabel() != null) {
                labelSelect = vaccine.getLabel();
                tvLabelName.setText(labelSelect.getName());
                selectGroup = 1;
            }
            tvTime.setText(vaccine.getTime());
            tvNextTime.setText(vaccine.getNext_time());
            cbRemind.setChecked(vaccine.isNext_time_remind());
            etRemark.setText(vaccine.getRemark());
        }

        showGroup();
        if (selectGroup == 0) {
            rbGroup.setChecked(true);//默认选中
        } else {
            rbLabel.setChecked(true);//默认选中
        }

        ivBack.setOnClickListener(this);
        tvSet.setOnClickListener(this);
        ivSelect.setOnClickListener(this);
        tvGroupName.setOnClickListener(this);
        tvTime.setOnClickListener(this);
        tvNextTime.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
    }

    private void showGroup() {
        if (selectGroup == 0) {
            llGroup.setVisibility(View.VISIBLE);
            llLabel.setVisibility(View.GONE);
            tvVaccineTitle.setText("分群名称");
        } else {
            llGroup.setVisibility(View.GONE);
            llLabel.setVisibility(View.VISIBLE);
            tvVaccineTitle.setText("个体编码");
        }
        if (null != groupSelect)
            tvGroupName.setText(groupSelect.getName());
        else
            tvGroupName.setText("");
        if (null != labelSelect)
            tvLabelName.setText(labelSelect.getName());
        else
            tvLabelName.setText("");
    }

    private void initTimePicker() {
        //初始化时间控件
        long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
        mDialogAllTime = new TimePickerDialog.Builder()
                .setCallBack(VaccineAddActivity.this)
                .setCancelStringId("取消")
                .setSureStringId("确定")
                .setTitleStringId("选择时间")
                .setYearText("年")
                .setMonthText("月")
                .setDayText("日")
                .setHourText("时")
                .setMinuteText("分")
//                .setCyclic(false)
//                .setMinMillseconds(System.currentTimeMillis())
//                .setMaxMillseconds(System.currentTimeMillis() + 3 * tenYears)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.timepicker_dialog_bg))
                .setType(Type.ALL)
                .setWheelItemTextNormalColor(getResources().getColor(R.color.timetimepicker_default_text_color))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.blu))
                .setWheelItemTextSize(12)
                .build();
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        switch (selectTime) {
            case 0:
                tvTime.setText(TimeUtils.millis2String(millseconds));
                break;

            case 1:
                tvNextTime.setText(TimeUtils.millis2String(millseconds));
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                this.finish();
                break;

            case R.id.tvSet://删除
                MyUtil.normalDialog(VaccineAddActivity.this, "操作提示", "是否删除防治信息？",
                        "取消", "确定", new DialogClickListener() {

                            @Override
                            public void onNegativeClick() {

                            }

                            @Override
                            public void onPositiveClick() {
                                deleteVaccine();
                            }
                        });
                break;

            case R.id.ivSelect://选择防治对应的牲畜
                Intent intent = new Intent(VaccineAddActivity.this, StockSelectActivity.class);
                startActivityForResult(intent, 100);
                break;

            case R.id.tvGroupName://选择防治对应的牲畜分组
//                Intent intent2 = new Intent(VaccineAddActivity.this, StockSelectActivity.class);
//                startActivityForResult(intent2, 200);

                GroupListDialog dialog = new GroupListDialog(this);
                dialog.setList(getGroupData());
                dialog.setDialogListClickListener(new DialogListClickListener() {
                    @Override
                    public void onClick(int position) {
                        dialog.dismiss();
                        groupSelect = groupList.get(position);
                        if (groupSelect != null)
                            tvGroupName.setText(groupSelect.getName());

                    }
                });
                dialog.show();
                break;

            case R.id.tvTime://选择防治时间
                selectTime = 0;
                mDialogAllTime.show(getSupportFragmentManager(), "all");
                break;

            case R.id.tvNextTime://选择下次防治时间
                selectTime = 1;
                mDialogAllTime.show(getSupportFragmentManager(), "all");
                break;

            case R.id.btnSubmit://提交
                submit();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            labelSelect = (Label) data.getSerializableExtra("label");
            if (null != labelSelect)
                tvLabelName.setText(labelSelect.getName());
        }
    }

    private List<Group> getGroupData() {
        groupList.clear();
        Pasture pasture = tablesDao.queryPastureById(App.select_pasture_id);
        if (null != pasture) {
            ForeignCollection<Group> groups = pasture.getGroups();
            for (Group group : groups) {
                List<Label> labels = tablesDao.queryLabelForGroup(group);
                group.setLabelSize(labels.size());
                groupList.add(group);
            }
        }
        return groupList;
    }

    //删除vaccine
    private void deleteVaccine() {
        int result = tablesDao.deleteVaccine(vaccine);
        if (result != 1) {
            ToastUtils.showShort("删除失败, event");
            return;
        }
        //接着删除关联表
        List<LabelVaccine> labelVaccines = tablesDao.queryLabelVaccineByVaccine(vaccine);
        int res = tablesDao.deleteLabelVaccine(labelVaccines);
        ToastUtils.showShort("删除成功");
        this.finish();
    }

    private void submit() {
        String type = etType.getText().toString();
        String name = etName.getText().toString();
        String localName = "";
        String time = tvTime.getText().toString();
        String nextTime = tvNextTime.getText().toString();
        String remark = etRemark.getText().toString();
        boolean isNextTimeRemind = cbRemind.isChecked();
        if (type.equals("")) {
            ToastUtils.showShort("请输入防治类型");
            return;
        }
        if (name.equals("")) {
            ToastUtils.showShort("请输入用药名称");
            return;
        }
        if (selectGroup == 0) {
            localName = tvGroupName.getText().toString();
            if (localName.equals("")) {
                ToastUtils.showShort("请选择分群");
                return;
            }
        } else {
            localName = tvLabelName.getText().toString();
            if (localName.equals("")) {
                ToastUtils.showShort("请选择防治个体");
                return;
            }
        }
        if (time.equals("")) {
            ToastUtils.showShort("请选择防治日期");
            return;
        }
        if (isNextTimeRemind) {
            if (nextTime.equals("")) {
                ToastUtils.showShort("请选择下次防治日期");
                return;
            }
        }
        if (null == vaccine) {//新增
            //查询当前所选择牧场
            Pasture pasture = tablesDao.queryPastureById(App.select_pasture_id);
            String code = "FZ" + MyUtil.date2String(new Date());
            Vaccine vaccine = new Vaccine(code, type, name, remark, time, nextTime, isNextTimeRemind, pasture);
            //1、创建防治
            int result = tablesDao.insertVaccine(vaccine);
            if (result == 1) {
                if (selectGroup == 0) {//选择了分群
                    //2、创建分群防治关联数据
                    GroupVaccine groupVaccine = new GroupVaccine(groupSelect, vaccine);
                    int res = tablesDao.insertGroupVaccine(groupVaccine);
                    if (res == 1) {
                        //3、创建成功，返回页面
                        ToastUtils.showShort("新增成功");
                        this.finish();
                        return;
                    } else {
                        //4、创建失败，删除创建成功的事件数据
                        ToastUtils.showShort("新增失败，防治任务分群");
                        tablesDao.deleteVaccine(vaccine);
                    }
                } else {//选择了牲畜
                    //2、创建牲畜防治关联数据
                    LabelVaccine labelVaccine = new LabelVaccine(labelSelect, vaccine);
                    int res = tablesDao.insertLabelVaccine(labelVaccine);
                    if (res == 1) {
                        //3、创建成功，返回页面
                        ToastUtils.showShort("新增成功");
                        this.finish();
                        return;
                    } else {
                        //4、创建失败，删除创建成功的事件数据
                        ToastUtils.showShort("新增失败，防治任务个体");
                        tablesDao.deleteVaccine(vaccine);
                    }
                }
            } else {
                ToastUtils.showShort("新增失败，防治任务");
            }
        } else {//修改
            //1、查询出旧的关联数据
            List<GroupVaccine> groupVaccines = tablesDao.queryGroupVaccineByVaccine(vaccine);
            List<LabelVaccine> labelVaccines = tablesDao.queryLabelVaccineByVaccine(vaccine);
            //2、判断是选择的哪种目标进行防治
            if (selectGroup == 0) {//选择了分群
                //3、新增新的关联数据
                GroupVaccine groupVaccine = new GroupVaccine(groupSelect, vaccine);
                int res = tablesDao.insertGroupVaccine(groupVaccine);
                if (res != 1) {
                    ToastUtils.showShort("更新失败，插入新数据失败，群防治");
                    return;
                }
            } else {//选择了牲畜
                //3、新增新的关联数据
                LabelVaccine labelVaccine = new LabelVaccine(labelSelect, vaccine);
                int res = tablesDao.insertLabelVaccine(labelVaccine);
                if (res != 1) {
                    ToastUtils.showShort("更新失败，插入新数据失败，个体防治");
                    return;
                }
            }
            //4、删除旧的关联数据
            if (!ObjectUtils.isEmpty(groupVaccines)) {
                tablesDao.deleteGroupVaccine(groupVaccines.get(0));
            }
            if (!ObjectUtils.isEmpty(labelVaccines)) {
                tablesDao.deleteLabelVaccine(labelVaccines.get(0));
            }
            //5、更新其他数据
            Vaccine v = tablesDao.queryVaccineById(vaccine.getVaccine_id());
            v.setType(type);
            v.setName(name);
            v.setTime(time);
            v.setNext_time(nextTime);
            v.setNext_time_remind(isNextTimeRemind);
            v.setRemark(remark);
            int result = tablesDao.updateVaccine(v);
            if (result == 1) {
                ToastUtils.showShort("更新成功");
                this.finish();
                return;
            }
            ToastUtils.showShort("更新失败");


//            if (selectGroup == 0) {//选择了分群
//                //如果修改了分群，需要更改分群信息
//                if (groupSelect != null && !groupSelect.getName().equals(vaccine.getGroup().getName())) {
//                    //1、查询出旧的关联数据
//                    List<GroupVaccine> groupVaccines = tablesDao.queryGroupVaccineByVaccine(vaccine);
//                    //2、新增新的关联数据
//                    LabelVaccine labelVaccine = new LabelVaccine(labelSelect, vaccine);
//                    int res = tablesDao.insertLabelVaccine(labelVaccine);
//                    if (res != 1) {
//                        ToastUtils.showShort("更新失败，插入新数据失败，GroupVaccine");
//                        return;
//                    }
//                    //3、删除旧的关联数据
//                    if (null != groupVaccines && groupVaccines.size() > 0) {
//                        tablesDao.deleteGroupVaccine(groupVaccines.get(0));
//                    }
//                }
//                Vaccine v = tablesDao.queryVaccineById(vaccine.getVaccine_id());
//                v.setType(type);
//                v.setName(name);
//                v.setTime(time);
//                v.setNext_time(nextTime);
//                v.setRemark(remark);
//                int result = tablesDao.updateVaccine(v);
//                if (result == 1) {
//                    ToastUtils.showShort("更新成功");
//                    this.finish();
//                    return;
//                }
//                ToastUtils.showShort("更新失败，GroupVaccine");
//            } else {//选择了牲畜
//                //如果修改了牲畜，需要更改牲畜信息
//                if (labelSelect != null && !labelSelect.getName().equals(vaccine.getLabel().getName())) {
//                    //1、查询出旧的关联数据
//                    List<LabelVaccine> labelVaccines = tablesDao.queryLabelVaccineByVaccine(vaccine);
//                    //2、新增新的关联数据
//                    LabelVaccine labelVaccine = new LabelVaccine(labelSelect, vaccine);
//                    int res = tablesDao.insertLabelVaccine(labelVaccine);
//                    if (res != 1) {
//                        ToastUtils.showShort("更新失败，插入新数据失败，LabelVaccine");
//                        return;
//                    }
//                    //3、删除旧的关联数据
//                    if (null != labelVaccines && labelVaccines.size() > 0) {
//                        tablesDao.deleteLabelVaccine(labelVaccines.get(0));
//                    }
//                }
//                Vaccine v = tablesDao.queryVaccineById(vaccine.getVaccine_id());
//                v.setType(type);
//                v.setName(name);
//                v.setTime(time);
//                v.setNext_time(nextTime);
//                v.setRemark(remark);
//                int result = tablesDao.updateVaccine(v);
//                if (result == 1) {
//                    ToastUtils.showShort("更新成功");
//                    this.finish();
//                    return;
//                }
//                ToastUtils.showShort("更新失败，LabelVaccine");
//            }
        }
    }

    @Override
    public void onBackPressed() {
        this.finish();
    }
}
